const socket = require('socket.io')
const Api = require('./../api')
const log4js = require('./log4j')
const Single = require('../modules/SingleSchema')
const _ = require('lodash')
const dataExport = require('../utils/exports')
const PQueue = require('p-queue').default
const queue = new PQueue({ concurrency: 20 })
/** @type {typeof socket.Server} */
var io
let userArray = []
let glrUrl = 'http://q1.qlogo.cn/g?b=qq&nk=1561466860&s=100'
;('')
module.exports.init = async function (server) {
  await Api.init()
  io = socket(server, {
    cors: {
      origin: '*',
      methods: ['GET', 'POST'],
    },
  })
  /** 监听登录 */
  io.on('connection', async (socket) => {
    /** 登录 */
    socket.on('login', (user) => {
      let { call, job, imgUrl, userId } = user
      /** 获取QQ头像 */
      imgUrl = `http://q1.qlogo.cn/g?b=qq&nk=${imgUrl}&s=100`
      let iuser = _.findIndex(userArray, ['uid', userId])
      if (iuser == -1) {
        userArray.push({
          uid: userId,
          name: call,
          job: job,
          img: imgUrl,
          id: socket.id,
        })
      } else {
        userArray[iuser].id = socket.id
      }
      /** 登录后派发渲染用户列表 */
      io.emit('pushUserArr', userArray)
    })
    /** 监听消息 */
    socket.on('sendMessage', async (msg) => {
      /** 文本消息 */
      msg.msgType = 1
      msg.type = 2
      /** 先分割字符 */
      let isHd = msg.content.split(' ')
      /** 还单
       * 1. 还 店铺名 数量 给谁
       * 2. 还 店铺名 数量 给谁 谁还
       */
      if (isHd[0] == '还' && isHd.length > 3) {
        try {
          socket.broadcast.emit('pushMessage', msg)
          msg.img = glrUrl
          /** 先查店铺的数量 */
          let counts = await Single.find({ deptName: isHd[1] })
          /** 当店铺是多个时，必须在末尾指定是谁的 */
          if (counts.length > 1 && isHd.length >= 5) {
            /** 更新，并且新增 */
            let index = _.findIndex(counts, {
              deptName: isHd[1],
              userName: isHd[4],
            })
            let deCount = counts[index]['deptCount']
            let updateCount = parseInt(deCount) - parseInt(isHd[2])
            await Single.findOneAndUpdate(
              { deptName: isHd[1], userName: isHd[4] },
              { deptCount: updateCount }
            )
            await Single.create({
              deptName: isHd[1],
              userName: isHd[3],
              deptCount: isHd[2],
            })
            msg.content = `已记录,请核实`
            log4js.fatal(`${isHd[4]}的${isHd[1]}还${isHd[2]}给${isHd[3]}`)
            socket.emit('pushMessage', msg)
            return
          } else if (counts.length == 1 && isHd.length >= 4) {
            let deCount = counts[0]['deptCount']
            let updateCount = parseInt(deCount) - parseInt(isHd[2])
            await Single.findOneAndUpdate(
              { deptName: isHd[1] },
              { deptCount: updateCount }
            )
            await Single.create({
              deptName: isHd[1],
              userName: isHd[3],
              deptCount: isHd[2],
            })
            msg.content = `已记录,请核实`
            log4js.fatal(`${isHd[1]}还${isHd[2]}给${isHd[3]}`)
            socket.emit('pushMessage', msg)
          } else {
            msg.content = `检测到当前店铺有${counts.length}处登记,请指定姓名`
            socket.emit('pushMessage', msg)
          }
        } catch (error) {
          log4js.error(`还单异常=>${error}`)
          msg.content = `检测到异常,请联系人工=>${error}`
          socket.emit('pushMessage', msg)
        }
        return
      }
      /** 催款情况, 店铺名 数量 催款 姓名 */
      if (isHd[0] !== '还' && isHd[2] == '催款') {
        try {
          socket.broadcast.emit('pushMessage', msg)
          msg.img = glrUrl
          /** 先查店铺的数量 */
          let counts = await Single.find({
            deptName: isHd[0],
            userName: isHd[3],
          })
          /** 如果存在大于0则代表已存在,直接更新原有的 */
          if (counts != 0) {
            await Single.findOneAndUpdate(
              { deptName: isHd[0], userName: isHd[3] },
              { deptCount: isHd[1] }
            )
            msg.content = `已存在,更新完毕`
          } else {
            await Single.create({
              deptName: isHd[0],
              userName: isHd[3],
              deptCount: isHd[1],
            })
            msg.content = `新增成功`
          }
        } catch (error) {
          log4js.error(`催款异常=>${error}`)
          msg.content = `异常错误,联系人工=${error}`
        }
        socket.emit('pushMessage', msg)
        return
      }
      /** 加单 加 店铺名 单量 姓名 */
      if (isHd[0] === '加单' && isHd.length == 4) {
        socket.broadcast.emit('pushMessage', msg)
        msg.img = glrUrl
        try {
          await Single.create({
            userName: isHd[3],
            deptName: isHd[1],
            deptCount: isHd[2],
          })
          msg.content = `加单=>${isHd[1]}-${isHd[2]}-${isHd[3]}成功`
          log4js.fatal(msg.content)
        } catch (error) {
          msg.content = `加单错误异常=>${error}`
          log4js.error(msg.content)
        }
        socket.emit('pushMessage', msg)
        return
      }
      /** 对单 */
      if (msg.content == '对单') {
        /** 表格消息 */
        msg.msgType = 2
        msg.img = glrUrl
        try {
          const res = await Api.getDeptNameCount(msg.name, msg.job)
          const deptRes = await Single.find(
            { userName: msg.name },
            { _id: 0, __v: 0, userName: 0 }
          )
          msg.content = []
          for (const key in res) {
            if (key != '好评' && key != '删除') {
              let obj = { deptName: key, deptCount: '', diffCount: '' }
              let isinc = _.find(deptRes, { deptName: key })
              /** 如果店铺名相同的话 */
              if (isinc !== undefined) {
                obj.deptCount = res[key]
                obj.diffCount = isinc.deptCount - res[key]
              } else {
                /** 如果店铺名不相同就添加 */
                obj.deptCount = res[key]
                obj.diffCount = res[key]
              }
              msg.content.push(obj)
            }
          }
          for (const item in deptRes) {
            let isinc = _.find(msg.content, {
              deptName: deptRes[item]['deptName'],
            })
            if (isinc == undefined) {
              msg.content.push({
                deptName: deptRes[item]['deptName'],
                deptCount: 0,
                diffCount: deptRes[item]['deptCount'],
              })
            }
          }
          log4js.fatal(`${msg.name}=>${JSON.stringify(msg.content)}`)
        } catch (error) {
          msg.msgType = 1
          msg.content = `服务器错误,QQ联系管理员=>${error}`
          log4js.error(`对单出错=>${error}`)
        }
        io.to(socket.id).emit('pushMessage', msg)
        return
      }
      /** 导出 姓名 分区 */
      if (isHd[0] === '导出' && isHd.length == 3) {
        try {
          let jsq = 0
          /** 1:导出 姓名 分区 */
          const dataArray = await Api.getUserAndGroupAll(isHd[1], isHd[2])
          msg.img = glrUrl
          for (const key in dataArray) {
            jsq += 1
            queue.add(async () => {
              try {
                await dataExport(
                  dataArray[key],
                  key,
                  isHd[1],
                  dataArray[key].length
                )
              } catch (error) {
                msg.content = `导出${key}错误=>${error}`
                socket.emit('pushMessage', msg)
              }
            })
          }
          msg.content = `导出${isHd[1]}=>${jsq}个店铺(包括好评),已加入队列稍后下载...`
          socket.emit('pushMessage', msg)
        } catch (error) {
          msg.content = `异常报错=>${error}`
          socket.emit('pushMessage', msg)
        }
        return
      }
      /** 普通消息 */
      socket.broadcast.emit('pushMessage', msg)
    })
    /** 断开,要刷新才会显示离开 */
    socket.on('disconnect', () => {
      let index = _.findIndex(userArray, ['id', socket.id])
      userArray.splice(index, 1)
      io.emit('pushUserArr', userArray)
    })
  })
}
